package com.zoffy.catdiarybackend.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.utils.IOUtils;
import com.zoffy.catdiarybackend.config.CosConfig;
import com.zoffy.catdiarybackend.service.AssetsService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
public class AssetsServiceImpl implements AssetsService {
    @Resource
    private RedisTemplate<Object,Object> redisTemplate;
    @Value("${tencent.bucket-name}")
    private String bucketName;
    @Resource
    private COSClient cosClient;

    @Override
    public byte[] getResource( String resourcePath) throws IOException {
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName,resourcePath);
        InputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosClient.getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        // 处理下载到的流
        // 这里是直接读取，按实际情况来处理
        byte[] bytes = null;
        try {
            bytes = IOUtils.toByteArray(cosObjectInput);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 用完流之后一定要调用 close()
            cosObjectInput.close();
        }
        return bytes;
    }
}
